package com.yami.shop.api.controller;

import com.yami.shop.bean.app.dto.CouponOrderDto;
import com.yami.shop.bean.dto.TtlCoupon;
import com.yami.shop.bean.model.Coupon;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.CouponService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/p/coupon")
@Tag(name = "优惠券接口")
public class CouponController {

    @Autowired
    private CouponService couponService;

    @GetMapping("/getCoupons")
    private ServerResponseEntity<List<Coupon>> getAllCoupon() {
        List<Coupon> couponList = couponService.getAllCoupon();
        return ServerResponseEntity.success(couponList);
    }
    @GetMapping("/getValCoupons")
    private ServerResponseEntity<List<Coupon>> getValCoupon() {
        String userId = SecurityUtils.getUser().getUserId();
        List<Coupon> couponList = couponService.getValCoupon(userId);
        return ServerResponseEntity.success(couponList);
    }

    @GetMapping("/getUserCoupons")
    private ServerResponseEntity<List<Coupon>> getUserCoupon() {
        String userId = SecurityUtils.getUser().getUserId();
        List<Coupon> couponList = couponService.getUserCoupon(userId);
        return ServerResponseEntity.success(couponList);
    }
    @PostMapping("/add")
    public ServerResponseEntity<Boolean> addCoupon(@RequestBody Coupon coupon) {
        couponService.insertCoupon(coupon);
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/getTtlCoupons")
    private ServerResponseEntity<List<TtlCoupon>> getTtlCoupon() {
        String userId = SecurityUtils.getUser().getUserId();
        List<TtlCoupon> couponList = couponService.getTtlCoupon(userId);
        return ServerResponseEntity.success(couponList);
    }

    @GetMapping("/getCouponOrderDto")
    private ServerResponseEntity<List<CouponOrderDto>> getCouponDto() {
        String userId = SecurityUtils.getUser().getUserId();
        List<CouponOrderDto> couponList = couponService.getCouponOrderDto(userId);
        for (CouponOrderDto coupon : couponList) {
            Date now = new Date();
            Date endDate = coupon.getEndDate();
            if (endDate.before(now)) {
                couponService.changeCouponStatus(coupon.getCouponId(), false);
            }
        }
        couponList = couponService.getCouponOrderDto(userId);

        return ServerResponseEntity.success(couponList);
    }
}
